import Utils from "../core/utils";

const { ccclass, property } = cc._decorator;

let Lerp = function (n1: number, n2: number, weight: number) {
    return n1 + (n2 - n1) * weight;
}
@ccclass
export class Fiter extends cc.Component {
    @property(cc.Node)
    target: cc.Node = null;
    @property
    inUpdate = false;

    @property
    effectOffset: cc.Vec2 = cc.v2(1, 1);

    @property
    fitWidth = false;
    @property
    fitHeigiht = false;

    protected lateUpdate(dt: number): void {
        if (!this.inUpdate) {
            return;
        }
        this.fit();
    }

    fit(): void {
        let target = this.target || Utils.game.node;
        if (this.fitHeigiht) {
            if (this.node.height > target.height) {
                let scale = target.height / this.node.height;
                this.node.setScale(
                    Lerp(1, scale, this.effectOffset.x),
                    Lerp(1, scale, this.effectOffset.y),
                );
            }
            else {
                this.node.setScale(1, 1);
            }
        }

        if (this.fitWidth) {
            if (this.node.width > target.width) {
                let scale = target.width / this.node.width;
                this.node.setScale(
                    Lerp(1, scale, this.effectOffset.x),
                    Lerp(1, scale, this.effectOffset.y),
                );
            }
            else {
                this.node.setScale(1, 1);
            }
        }
    }
};